<?php

namespace app\common\model;

use fast\Random;
use think\Model;
use xing\payment\drive\PayFactory;


class Order extends Model
{

    

    

    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'order_type_text',
        'paytype_text',
        'status_text',
        'paytime_text',
        'completetime_text',
        'canceltime_text'
    ];
    

    
    public function getOrderTypeList()
    {
        return ['0' => __('Order_type 0'), '1' => __('Order_type 1')];
    }

    public function getPaytypeList()
    {
        return ['0' => __('Paytype 0')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '3' => __('Status 3'), '-1' => __('Status -1')];
    }


    public function getOrderTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_type']) ? $data['order_type'] : '');
        $list = $this->getOrderTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytype']) ? $data['paytype'] : '');
        $list = $this->getPaytypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCompletetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['completetime']) ? $data['completetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCompletetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function goodscategory()
    {
        return $this->belongsTo('GoodsCategory', 'goods_category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function getStatusText($status)
    {
        $statusArr = [
            '-1' => '开启',
            '0' => '关闭',
            '1' => '关闭',
            '3' => '关闭',
        ];
        return isset($statusArr[$status]) ? $statusArr[$status] : false;
    }

    /**
     * 创建订单
     * @param $data
     * @param $user
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function createOrder($data, $user)
    {
        // 支付配置
        $site = config('site');

        // 商品信息
        $goods = \app\common\model\Goods::get(['id'=>$data['id']]);

        // 分类信息
        $goodsCategory = GoodsCategory::get(['id'=>$goods['goods_category_id']]);

        // 微信配置
        $config = [
            'title' => $goods['name'],
            'appId' => $site['applets_appid'],
            'mchId' => $site['mchId'],
            'notifyUrl' => request()->domain().'/homeapi/wxnotify',
            // 请换成你自己的相应的文证书件地址
            'SSL_CERT_PATH' =>  request()->domain().'/wxpem/apiclient_cert.pem',
            'SSL_KEY_PATH' => request()->domain().'/wxpem/apiclient_key.pem',
            'key'=>$site['mchkey'],// 支付秘钥
        ];
        // 小程序、公众号支付等JSAPI需要额外加上用户openId
        $config['openId'] = $user['openid'];

        // 订单号
        $ordersn = 'SN'.Random::alnum(8);

        /* 初始化 */
        $payName = 'weChatPay'; // 支付驱动代码
        $payInstance = PayFactory::getInstance($payName)->init($config); //支付驱动 的配置，详情看配置篇，小程序需要在微信支付配置的基础上多加openId
        /* 生成签名 */
        // 测试
        // $goods['price'] = 0.1;
        $orderInfo = $payInstance->set($ordersn, $goods['price'], $goods['name'])->getMiniProgramParam();
        if(empty($orderInfo)) return false;
        $orderInfo = json_decode($orderInfo, true);
        if(empty($orderInfo['nonceStr']) || empty($orderInfo['package'])) return false;

        // 本地订单写入
        $order = [
            'user_id' => $user['user_id'],
            'ordersn' => $ordersn,
            'goods_category_id' => $goodsCategory['id'],
            'goods_id' => $goods['id'],
            'goods_name' => $goods['name'],
            'goods_price' => $goods['price'],
            'total' => 1,
            'paytype' => 0,
            'prepay_id' => substr($orderInfo['package'], strpos($orderInfo['package'], '=')+1),
            'status' => 0,
            'createtime' => time(),
        ];
        db('order')
            ->insert($order);

        return $orderInfo;
    }

    /**
     * 订单列表
     */
    public static function getList($data)
    {
        $where = '1=1';
        $order = 'a.id desc';
        $page  = isset($data['page']) && !empty($data['page']) ? intval($data['page']) : 1;
        $limit  = isset($data['limit']) && !empty($data['limit']) ? intval($data['limit']) : 10;
        $start = ($page-1)*$limit;

        if(isset($data['user_id']) && !empty($data['user_id']))
        {
            $where .= " and a.user_id={$data['user_id']}";
        }
        if(isset($data['ordersn']) && !empty($data['ordersn']))
        {
            $where .= " and a.ordersn like '%{$data['ordersn']}%'";
        }
        if(isset($data['goods_category_id']) && !empty($data['goods_category_id']))
        {
            $where .= " and a.goods_category_id={$data['goods_category_id']}";
        }
        if(isset($data['goods_id']) && !empty($data['goods_id']))
        {
            $where .= " and a.goods_id={$data['goods_id']}";
        }
        if(isset($data['goods_name']) && !empty($data['goods_name']))
        {
            $where .= " and a.goods_name like '%{$data['goods_name']}%'";
        }
        if(isset($data['status']) && !empty($data['status']))
        {
            $where .= " and a.status='{$data['status']}'";
        }

        $field = "a.*, c.name as goods_category_name, d.username, d.mobile";

        $list = db('order')
            ->alias('a')
            ->join('goods b', 'a.goods_id = b.id')
            ->join('goods_category c', 'a.goods_category_id = c.id')
            ->join('user d', 'a.user_id = d.id')
            ->where($where)
            ->order($order)
            ->limit($start, $limit)
            ->field($field)
            ->select();
        if(!empty($list))
        {
            foreach ($list as &$v)
            {
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['statusText'] = self::getStatusText($v['status']);
            }
            unset($v);
        }

        $total = db('order')
            ->alias('a')
            ->join('goods b', 'a.goods_id = b.id')
            ->join('goods_category c', 'a.goods_category_id = c.id')
            ->join('user d', 'a.user_id = d.id')
            ->where($where)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
        ];

    }

}
